package com.hrm.system.shiro.realm;

import com.hrm.common.shiro.realm.HrmRealm;
import com.hrm.domain.system.Permission;
import com.hrm.domain.system.User;
import com.hrm.domain.system.response.ProfileResult;
import com.hrm.system.service.PermissionService;
import com.hrm.system.service.UserService;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserRealm extends HrmRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //认证方法
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String mobile = upToken.getUsername();
        String password = new String(upToken.getPassword());
        //查询用户
        User user = userService.findByMobile(mobile);
        //认证
        ProfileResult result = null;
        if (user != null && password.equals(user.getPassword())) {
            if ("user".equals(user.getLevel())) {
                result = new ProfileResult(user);
            } else {
                Map<String, Object> map = new HashMap<>();
                if ("coAdmin".equals(user.getLevel())) {
                    map.put("enVisible", "1");
                }
                List<Permission> permissions = permissionService.findPermissions(map);
                result = new ProfileResult(user, permissions);
            }
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(result, user.getPassword(), this.getName());
            return info;
        }
        //否则跳出异常
        return null;
    }
}
